<?php

class Permission {

	public static function getAll( $user_group_id ) {

		// Get All Routes
		$routes = Route::getRoutes();

		// Modules Data Container
		$modules = array();

		// Render All routes
		foreach($routes as $value) {

			// Route Method e.g. GET, POST
			$method = $value->getMethods()[0];

			// Route Path e.g. category/{id}
			$path 	= $value->getPath();

			// Check if Route Path is not included in common Routes
			if( !in_array($path, explode(',',Constant::COMMON_ROUTES)) ) {

				// Disect Path's URI
				$parts = explode('/', $path);

				// Count number of disected Path's URI
				$count = count($parts);

				// If Count is One ( 1 ) and Method is GET, that's the main Module's path
				// e.g category/{id}, category/{id}/edit = The Main Module Path is 'category'
				if( $count == 1 && $method == 'GET' ) {

					// Main Module Path
					$route = $parts[0];

					// Module title based on Main Path
					$title = ucwords(str_replace('-', ' ', str_replace('_', ' ', $route)));

					$user_permission = array();

					if( $user_group_id  > 0 ) {
						$user_group = UserGroup::find($user_group_id);
						if( $user_group->count() )
							$user_permission = $user_group->userPermission()->where('route', '=', $route)->first();
					}

					$modules[$route] = [
						'title'	=> $title,
						'route' => $route,
						'icon'	=> !empty($user_permission->icon) ? $user_permission->icon : '', 
						'create'=> !empty($user_permission->create),
						'read'	=> !empty($user_permission->read),
						'update'=> !empty($user_permission->update),
						'delete'=> !empty($user_permission->delete)
					];
				}
			}

		}
		
		return $modules;
	}
	
	public static function check( $route, $action, $user_group_id = null) {
		
		if( empty($user_group_id) ) {
			
			if( !Auth::check())
				return false;
			
			$user_group_id = Auth::user()->USER_GROUP_id;
		}
	
		
		$module = self::getAll( $user_group_id );
		
		return !empty( $module[$route][$action] );
	}
}